package com.hcm.kernel.wechat;

import com.hcm.kernel.util.MD5Util;
import com.hcm.kernel.util.SystemConfig;
import com.hcm.kernel.wechat.util.HttpUtil;
import org.apache.http.NameValuePair;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.LoggerFactory;

import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理所有与微信支付相关的
 */
public class PayAPI {

    public static String pay(String body,String pay,String openid,String appid,String mch_id,String url_,String random,String ip){
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        if(!SystemConfig.getBoolean("use_default_interface"))
            url = SystemConfig.getString("pay");

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("appid",appid));//appid
        nvps.add(new BasicNameValuePair("body",body));//商品描述
        nvps.add(new BasicNameValuePair("mch_id",mch_id));//商户号
        nvps.add(new BasicNameValuePair("nonce_str",random));//随机字符串
        nvps.add(new BasicNameValuePair("notify_url",url_));//通知地址，成功返回地址
        nvps.add(new BasicNameValuePair("openid",openid));
        nvps.add(new BasicNameValuePair("out_trade_no",random));//商户订单号
        nvps.add(new BasicNameValuePair("spbill_create_ip",ip));//终端 IP
        nvps.add(new BasicNameValuePair("total_fee",String.valueOf(Integer.parseInt(pay)*100)));//总金额
        nvps.add(new BasicNameValuePair("trade_type","JSAPI"));//交易类型  JSAPI、NATIVE、APP
        //签名生成
        String sign = HttpUtil.toUrl(nvps);
        sign = sign + "key="+SystemConfig.getString("key");
        sign = MD5Util.encode(sign).toUpperCase();

        nvps.add(new BasicNameValuePair("sign",sign));//签名

        //转为xml
        String xml = HttpUtil.toXml(nvps);
        System.out.println(xml);
        try {
            return HttpUtil.execute(url, new StringEntity(xml, "utf-8"));
        } catch (UnsupportedCharsetException e) {
            LoggerFactory.getLogger(PayAPI.class).error("Pay error:{}",e.getMessage());
        }
        return "";
    }

}
